package org.ccay.validator.validators;

import org.ccay.core.ioc.Ccay;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

/**
 * 
 * igrid重复数据验证
 * 
 * 
 * @since 2014-1-15
 */
public class IgridDuplicateDataValidator extends FieldValidatorSupport {
	/**
	 * spring表达式对象
	 */
	private ExpressionParser parser = new SpelExpressionParser();
	private String beanId;

	public void setBeanId(String beanId) {
		this.beanId = beanId;
	}

	public String getBeanId() {
		return beanId;
	}

	private String methodName;

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String getethodName() {
		return methodName;
	}

	public void validate(Object object) throws ValidationException {

		Object service = Ccay.getContext().getBean(beanId);
		String fieldName = getFieldName();
		Object value = getFieldValue(fieldName, object);
		// 如果为空 那么直接返回
		if (value == null || "".equals(value.toString())) {
			return;
		}
		StringBuilder buffer = new StringBuilder("#obj.").append(methodName).append("(");
		// 上下文
		EvaluationContext context = new StandardEvaluationContext();
		context.setVariable("obj", service);
		// 参数拼接
		buffer.append("#p1");
		context.setVariable("p1", object);
		buffer.append(")");
		String expresson = buffer.toString();

		Expression exp = parser.parseExpression(expresson);
		// 取得结果
		Object returnVal = exp.getValue(context);

		// 验证不通过 插入异常信息
		if (returnVal != null & returnVal != "") {
			addFieldError(fieldName, object);
		}
	}
}
